package com.sicheng.algorithm.string;

import java.util.HashMap;

public class LengthOfLongestSubstring {
    public static void main(String[] args) {
        System.out.println(lengthOfLongestSubstring("abcefoaelkjhuia"));
        System.out.println(lengthOfLongestSubstring("abba"));
    }

    public static int lengthOfLongestSubstring(String s) {
        if (s.length() <= 1)
            return s.length();

        int left = 0, right = 0, maxLength = 1;
        HashMap<Character, Integer> window = new HashMap<>();
        while (right < s.length()) {
            if (s.length() - left - 1 < maxLength)
                break;
            if (window.containsKey(s.charAt(right))) {
                left = Math.max(left, window.get(s.charAt(right)) + 1);
            }
            window.put(s.charAt(right), right);
            maxLength = Math.max(maxLength, right - left + 1);
            right++;
        }
        return maxLength;
    }


}
